﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Util;
using LM.YF.K3Cloud.Plugin.Models;
using System;
using System.ComponentModel;

namespace LM.YF.K3Cloud.Plugin
{
    /// <summary>
    /// 分摊成本结算单提货费
    /// <author>鹿奔</author>
    /// <date>240117</date>
    /// </summary>
    [HotUpdate, Description("分摊成本结算单提货费操作服务插件"), Obsolete("该插件已作废")]
    public class CostDeliveryFeeOperationServicePlugin : AbstractOperationServicePlugIn
    {
        internal readonly ElementKeySchema Header_TiHuoFei = new ElementKeySchema
        {
            DbKey = "F_FEE_TI_HUO",
            FormKey = "F_fee_ti_huo",
            OrmKey = "F_fee_ti_huo"
        };
        internal readonly ElementKeySchema Entry_TiHuoFei = new ElementKeySchema
        {
            DbKey = "F_FEE_TI_HUO2",
            FormKey = "F_fee_ti_huo2",
            OrmKey = "F_fee_ti_huo2"
        };
        internal readonly ElementKeySchema Entry_JiaoHuoShuLiang = new ElementKeySchema
        {
            DbKey = "F_DELIVER_QTY",
            FormKey = "F_deliver_qty",
            OrmKey = "F_deliver_qty"
        };

        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            e.FieldKeys.Add(Header_TiHuoFei.FormKey);
        }

        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);
            //if (FormOperation.OperationId == Kingdee.BOS.Core.Metadata.FormElement.FormOperation.Operation_Audit)
            //{
            UpdateDeliveryFee(e);
            //}
        }

        private void UpdateDeliveryFee(AfterExecuteOperationTransaction e)
        {
            var rows = e.SelectedRows;
            foreach (var row in rows)
            {
                var id = row.DataEntity["Id"];
                // 获取提货费总额和交货数量总量
                var thfTotal = Convert.ToDecimal(row.DataEntity[Header_TiHuoFei.OrmKey]);
                var sql = $@"select sum({Entry_JiaoHuoShuLiang.DbKey})
                    from T_AP_PAYABLEENTRY
                    where FID = {id};";
                var jhslTotal = DBUtils.ExecuteScalar<float>(Context, sql, 0);
                // 更新分录提货费
                var sql2 = $@"update T_AP_PAYABLEENTRY
                    set {Entry_TiHuoFei.DbKey} = iif({jhslTotal} = 0, 0, {thfTotal}/{jhslTotal}*{Entry_JiaoHuoShuLiang.DbKey})
                    where FID = {id};";
                DBUtils.Execute(Context, sql2);
            }
        }
    }
}
